<template>
  <el-card class="chart-card">
    <h3 class="chart-title">投票活动状态分布</h3>
    <div class="chart-container">
      <canvas ref="ringChartRef"></canvas>
    </div>
  </el-card>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { Chart, registerables } from 'chart.js';
import { getVoteStatus } from '@/api/business/dashboard';


Chart.register(...registerables);
const ringChartRef = ref(null);
let chartInstance = null;
const statusData = ref([]);

// 获取数据
onMounted(async () => {
getVoteStatus().then(response => {
    statusData.value = response.data
  })
});
// 绘制环形图
const renderChart = () => {
  if (chartInstance) chartInstance.destroy();
  const labels = statusData.value.map(item => item.statusName);
  const data = statusData.value.map(item => item.percentage);
  const colors = statusData.value.map(item => item.color);

  chartInstance = new Chart(ringChartRef.value, {
    type: 'doughnut', // 环形图
    data: { labels, datasets: [{ data, backgroundColor: colors, borderWidth: 0 }] },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      cutout: '70%', // 环形大小
      plugins: {
        legend: {
          position: 'right', // 图例在右侧
          labels: { padding: 20, font: { size: 12 } }
        },
        tooltip: {
          callbacks: {
            label: (ctx) => {
              const item = statusData.value[ctx.dataIndex];
              return `${item.statusName}：${item.count} 个 (${item.percentage}%)`;
            }
          }
        }
      }
    }
  });
};

watch(statusData, renderChart);
</script>

<style scoped>
.chart-card { height: 300px; padding: 15px; }
.chart-title { font-size: 16px; color: #333; margin-bottom: 10px; }
.chart-container { width: 100%; height: 200px; }
</style>